package com.qingcloud.adminbackend.controller;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.base.LoginRequest;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.entity.user.SysUser;
import com.qingcloud.adminbackend.entity.userrole.UserRoles;
import com.qingcloud.adminbackend.service.ISysUserService;
import com.qingcloud.adminbackend.utils.CookieUtil;
import com.qingcloud.base.constant.SecurityConstants;
import com.qingcloud.base.passwordencode.Md5PasswordEncoder;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * <p>
 * 登录前端控制器
 * </p>
 *
 * @author wangjinnan
 * @since 2018-11-19
 */
@RestController
@RequestMapping("/waming")
public class LoginController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private Md5PasswordEncoder md5PasswordEncoder;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private Producer captchaProducer;

    @ApiOperation(value = "用户登录接口", notes = "用户登录接口")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginRequest loginRequest, HttpServletResponse response) throws UnsupportedEncodingException {
        //用户名和密码不能为空
        if (StringUtils.isEmpty(loginRequest.getUsername()) || StringUtils.isEmpty(loginRequest.getPassword())) {
            return new AjaxResult(WamingConstant.FAILURE, "用户名或密码不能为空", "");
        }
        //先查询用户
        SysUser sysUser = sysUserService.findByUserNameOrPhone(loginRequest.getUsername());
        if (sysUser == null) {
            return new AjaxResult(WamingConstant.FAILURE, "未找到此用户", "");
        }
        //检查是否是蛙鸣用户
//        if (sysUser.getUserType() != UserTypeEnum.WAMING_USER.code) {
//            return new AjaxResult(WamingConstant.FAILURE, "无权登录此平台", "");
//        }
        //比对用户密码
        if ((!sysUser.getUserPassword().equals(md5PasswordEncoder.encodePassword(loginRequest.getPassword(), sysUser.getId())))
                && (!sysUser.getUserPassword().equals(md5PasswordEncoder.encodePassword(loginRequest.getPassword(), sysUser.getUserName())))) {
            return new AjaxResult(WamingConstant.FAILURE, "用户密码不正确", "");
        }
        // 用户名ID
        CookieUtil.addCookie(response, CookieUtil.USER_ID_KEY, sysUser.getId(), 0);
        // 用户名
        CookieUtil.addCookie(response, CookieUtil.USER_NAME_KEY, sysUser.getUserName(), 0);

        CookieUtil.addCookie(response, CookieUtil.USER_FULL_NAME, URLEncoder.encode(sysUser.getFullName(), "UTF-8"), 0);
        //用户登录token，后续处理
        String token = IdUtil.simpleUUID();
        CookieUtil.addCookie(response, CookieUtil.TOKEN_KEY, token, 0);
        //登录状态更新
        sysUserService.updateLoginInfoById(sysUser.getId());
        UserRoles allRoles = sysUserService.getAllRoles(sysUser.getId());
        allRoles.setAdminFlag(sysUser.getAdminFlag());
        allRoles.setIsAdmin(SecurityConstants.ADMIN_USER_NAME.equals(sysUser.getUserName()) ? 1 : 0);
        allRoles.setUserType(sysUser.getUserType());
        return new AjaxResult(WamingConstant.SUCCESS, "", allRoles);
    }

    @ApiOperation(value = "用户登出接口", notes = "用户登出接口")
    @PostMapping("/logout")
    public AjaxResult logout(HttpServletRequest request, HttpServletResponse response) {
        //获取用户ID，后续处理
        String userId = CookieUtil.getUserId(request);
        // 用户名ID
        CookieUtil.removeCookie(response, CookieUtil.USER_ID_KEY);
        // 用户名
        CookieUtil.removeCookie(response, CookieUtil.USER_NAME_KEY);
        //用户登录token
        CookieUtil.removeCookie(response, CookieUtil.TOKEN_KEY);
        //设置登录状态
        sysUserService.loguot(userId);
        return new AjaxResult(WamingConstant.SUCCESS, "", "");
    }

    @ApiOperation(value = "验证码图片接口", notes = "验证码图片接口")
    @GetMapping(value = "/kaptcha")
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/png");
        // create the text for the image
        String capText = captchaProducer.createText();
        logger.info("******************验证码是: {}******************", capText);
        //Cookie设置
        CookieUtil.addCookie(response, "code", capText, 0);
        // store the text in the session
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        // create the image with the text
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        // write the data out
        ImageIO.write(bi, "png", response.getOutputStream());
        try {
            out.flush();
        } finally {
            out.close();
        }

    }
}

